<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Console\Commands;

use App\Enums\CheckStatusEnum;
use App\Models\UserProfile;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class CensusUsersAge extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'census:user_ages';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计用户年龄';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $users = UserProfile::query()
            ->select('birthday')
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT)
            ->get();
        $result = [
            '18' => 0,
            '19_30' => 0,
            '31_40' => 0,
            '41_50' => 0,
            '51_60' => 0,
            '60' => 0,
        ];
        /** @var UserProfile $user */
        $now = time();
        foreach ($users as $user) {
            $birthday = $user->birthday;
            $birthdayTime = strtotime($birthday);
            $diff = $now - $birthdayTime;
            if ($diff < 19 * 365 * 24 * 3600) {
                ++$result['18'];
            }
            if ($diff >= 19 * 365 * 24 * 3600 && $diff < 31 * 365 * 24 * 3600) {
                ++$result['19_30'];
            }
            if ($diff >= 31 * 365 * 24 * 3600 && $diff < 41 * 365 * 24 * 3600) {
                ++$result['31_40'];
            }
            if ($diff >= 41 * 365 * 24 * 3600 && $diff < 51 * 365 * 24 * 3600) {
                ++$result['41_50'];
            }
            if ($diff >= 51 * 365 * 24 * 3600 && $diff < 61 * 365 * 24 * 3600) {
                ++$result['60'];
            }
        }
        Redis::set(config('census.user_age_key'), json_encode($result));
        return 0;
    }
}
